#!/bin/bash

LOCK_PATH=/run/lock/kiwix
mkdir -p $LOCK_PATH

WAITLOCK="$LOCK_PATH/make-kiwix-lib-wait.LCK";
RUNLOCK="$LOCK_PATH/kiwix-lib-access.LCK";
KIWIXLIB={{ kiwix_library_xml }}

exec 200>$WAITLOCK;
exec 201>$RUNLOCK;

if flock -n -e 200; then :
  echo 'Waiting to run iiab-make-kiwix-lib.py'
  # wait for up to 5 min
  flock -x -w 300 201
  flock -u 200 # unlock queue
  echo "Now running iiab-make-kiwix-lib.py"
  # write to {{ kiwix_library_xml }}.tmp to minimize kiwix down
  # zim map could be out of sync for a few seconds
  # using new version that does deltas
  if [ -f $KIWIXLIB ]; then
    cp $KIWIXLIB $KIWIXLIB.tmp
    /usr/bin/iiab-make-kiwix-lib.py $@
  else
    /usr/bin/iiab-make-kiwix-lib.py -f # force rebuild of library.xml
  fi
  /usr/bin/systemctl stop kiwix-serve
  if [ -f $KIWIXLIB ]; then
    rm $KIWIXLIB
  fi
  mv $KIWIXLIB.tmp $KIWIXLIB
  /usr/bin/systemctl start kiwix-serve
else
  echo "Can't get wait lock for iiab-make-kiwix-lib.py";
  exit 1;
fi
echo 'Finished making Kiwix library.xml'
exit 0
